<template>
  <div class="maintenance-standards">
    <div class="page-header">
      <h2>维修标准设置</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        添加标准
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总标准数"
          :value="statistics.totalStandards"
          :change="statistics.totalChange"
          icon="ant-design:setting-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="启用标准"
          :value="statistics.activeStandards"
          :change="statistics.activeChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均评分"
          :value="statistics.averageRating"
          :change="statistics.ratingChange"
          icon="ant-design:star-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="使用次数"
          :value="statistics.usageCount"
          :change="statistics.usageChange"
          icon="ant-design:bar-chart-outlined"
          color="#722ed1"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <FormItem label="标准名称">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入标准名称"
            allow-clear
          />
        </FormItem>
        <FormItem label="维修类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择维修类型"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="electrical">电气维修</SelectOption>
            <SelectOption value="plumbing">水管维修</SelectOption>
            <SelectOption value="appliance">家电维修</SelectOption>
            <SelectOption value="furniture">家具维修</SelectOption>
            <SelectOption value="structure">结构维修</SelectOption>
            <SelectOption value="other">其他</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="active">启用</SelectOption>
            <SelectOption value="inactive">停用</SelectOption>
            <SelectOption value="draft">草稿</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="优先级">
          <Select
            v-model:value="searchForm.priority"
            placeholder="请选择优先级"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="low">低</SelectOption>
            <SelectOption value="medium">中</SelectOption>
            <SelectOption value="high">高</SelectOption>
            <SelectOption value="urgent">紧急</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 标准表格 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredStandards"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="standard-info">
              <div class="standard-name">{{ record.name }}</div>
              <div class="standard-desc">{{ record.description }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'rating'">
            <div class="rating-info">
              <span class="rating-score">{{ record.rating }}</span>
              <span class="rating-count">({{ record.ratingCount }}条评价)</span>
            </div>
          </template>
          <template v-else-if="column.key === 'completionRate'">
            <Progress
              :percent="record.completionRate"
              :status="getCompletionStatus(record.completionRate)"
              size="small"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="editStandard(record)">
                编辑
              </Button>
              <Button type="link" size="small" @click="viewItems(record)">
                检查项
              </Button>
              <Button
                v-if="record.status === 'inactive'"
                type="link"
                size="small"
                @click="activateStandard(record)"
              >
                启用
              </Button>
              <Button
                v-else-if="record.status === 'active'"
                type="link"
                size="small"
                @click="deactivateStandard(record)"
              >
                停用
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新建/编辑标准弹窗 -->
    <Modal
      v-model:open="showAddModal"
      :title="isEdit ? '编辑维修标准' : '添加维修标准'"
      width="700px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="标准名称" name="name">
              <Input v-model:value="form.name" placeholder="请输入标准名称" />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="维修类型" name="type">
              <Select v-model:value="form.type" placeholder="选择维修类型">
                <SelectOption value="electrical">电气维修</SelectOption>
                <SelectOption value="plumbing">水管维修</SelectOption>
                <SelectOption value="appliance">家电维修</SelectOption>
                <SelectOption value="furniture">家具维修</SelectOption>
                <SelectOption value="structure">结构维修</SelectOption>
                <SelectOption value="other">其他</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="优先级" name="priority">
              <Select v-model:value="form.priority" placeholder="选择优先级">
                <SelectOption value="low">低</SelectOption>
                <SelectOption value="medium">中</SelectOption>
                <SelectOption value="high">高</SelectOption>
                <SelectOption value="urgent">紧急</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="状态" name="status">
              <Select v-model:value="form.status" placeholder="选择状态">
                <SelectOption value="active">启用</SelectOption>
                <SelectOption value="inactive">停用</SelectOption>
                <SelectOption value="draft">草稿</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="标准描述" name="description">
          <Textarea
            v-model:value="form.description"
            placeholder="请输入标准描述"
            :rows="3"
          />
        </FormItem>
        <FormItem label="维修步骤" name="steps">
          <Textarea
            v-model:value="form.steps"
            placeholder="请输入维修步骤"
            :rows="4"
          />
        </FormItem>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="预计工时" name="estimatedHours">
              <Input
                v-model:value="form.estimatedHours"
                placeholder="预计工时（小时）"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="所需工具" name="tools">
              <Input v-model:value="form.tools" placeholder="所需工具" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="注意事项" name="notes">
          <Textarea
            v-model:value="form.notes"
            placeholder="注意事项"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 标准详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="标准详情"
      width="800px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="标准名称">
          {{ selectedStandard?.name }}
        </DescriptionsItem>
        <DescriptionsItem label="维修类型">
          <Tag :color="getTypeColor(selectedStandard?.type)">
            {{ getTypeText(selectedStandard?.type) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="优先级">
          <Tag :color="getPriorityColor(selectedStandard?.priority)">
            {{ getPriorityText(selectedStandard?.priority) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="状态">
          <Tag :color="getStatusColor(selectedStandard?.status)">
            {{ getStatusText(selectedStandard?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="预计工时">
          {{ selectedStandard?.estimatedHours }}小时
        </DescriptionsItem>
        <DescriptionsItem label="所需工具">
          {{ selectedStandard?.tools }}
        </DescriptionsItem>
        <DescriptionsItem label="评分">
          {{ selectedStandard?.rating }} ({{
            selectedStandard?.ratingCount
          }}条评价)
        </DescriptionsItem>
        <DescriptionsItem label="完成率">
          <Progress
            :percent="selectedStandard?.completionRate"
            :status="getCompletionStatus(selectedStandard?.completionRate)"
            size="small"
          />
        </DescriptionsItem>
        <DescriptionsItem label="标准描述" :span="2">
          {{ selectedStandard?.description }}
        </DescriptionsItem>
        <DescriptionsItem label="维修步骤" :span="2">
          {{ selectedStandard?.steps }}
        </DescriptionsItem>
        <DescriptionsItem label="注意事项" :span="2">
          {{ selectedStandard?.notes || '无' }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 检查项弹窗 -->
    <Modal
      v-model:open="showItemsModal"
      title="检查项设置"
      width="800px"
      @ok="handleSaveItems"
      @cancel="showItemsModal = false"
    >
      <div class="items-header">
        <Button type="primary" @click="addItem">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加检查项
        </Button>
      </div>
      <Table
        :columns="itemColumns"
        :data-source="inspectionItems"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'required'">
            <Checkbox v-model:checked="record.required" />
          </template>
          <template v-else-if="column.key === 'score'">
            <Input
              v-model:value="record.score"
              type="number"
              min="1"
              max="10"
              style="width: 60px"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <Button type="link" size="small" @click="removeItem(index)">
              删除
            </Button>
          </template>
        </template>
      </Table>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

// 状态管理
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showItemsModal = ref(false);
const isEdit = ref(false);
const selectedStandard = ref(null);

// 表单引用
const formRef = ref();

// 统计数据
const statistics = reactive({
  totalStandards: 25,
  totalChange: 3,
  activeStandards: 18,
  activeChange: 2,
  averageRating: 4.5,
  ratingChange: 0.2,
  usageCount: 156,
  usageChange: 12,
});

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  priority: '',
});

// 标准表单
const form = reactive({
  name: '',
  type: '',
  priority: 'medium',
  status: 'active',
  description: '',
  steps: '',
  estimatedHours: '',
  tools: '',
  notes: '',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入标准名称' }],
  type: [{ required: true, message: '请选择维修类型' }],
  priority: [{ required: true, message: '请选择优先级' }],
  status: [{ required: true, message: '请选择状态' }],
  description: [{ required: true, message: '请输入标准描述' }],
  steps: [{ required: true, message: '请输入维修步骤' }],
  estimatedHours: [{ required: true, message: '请输入预计工时' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 标准数据
const standards = ref([
  {
    id: 1,
    name: '空调维修标准',
    description: '空调制冷系统维修的标准流程',
    type: 'appliance',
    priority: 'high',
    status: 'active',
    rating: 4.8,
    ratingCount: 45,
    completionRate: 92,
    estimatedHours: 2,
    tools: '万用表、螺丝刀、制冷剂',
    steps: '1. 检查电源\n2. 检查制冷剂\n3. 清洁滤网\n4. 测试运行',
    notes: '注意安全，确保断电操作',
  },
  {
    id: 2,
    name: '水管维修标准',
    description: '水管漏水维修的标准流程',
    type: 'plumbing',
    priority: 'medium',
    status: 'active',
    rating: 4.6,
    ratingCount: 32,
    completionRate: 88,
    estimatedHours: 1.5,
    tools: '扳手、密封胶、水管',
    steps: '1. 关闭水源\n2. 拆卸损坏部件\n3. 更换密封圈\n4. 测试密封性',
    notes: '确保水源完全关闭',
  },
  {
    id: 3,
    name: '电气维修标准',
    description: '电气设备维修的标准流程',
    type: 'electrical',
    priority: 'urgent',
    status: 'active',
    rating: 4.7,
    ratingCount: 28,
    completionRate: 95,
    estimatedHours: 3,
    tools: '万用表、绝缘胶带、电线',
    steps: '1. 断电检查\n2. 检查线路\n3. 更换损坏部件\n4. 通电测试',
    notes: '必须断电操作，注意安全',
  },
  {
    id: 4,
    name: '家具维修标准',
    description: '家具损坏维修的标准流程',
    type: 'furniture',
    priority: 'low',
    status: 'inactive',
    rating: 4.4,
    ratingCount: 15,
    completionRate: 85,
    estimatedHours: 1,
    tools: '螺丝刀、胶水、木工工具',
    steps: '1. 检查损坏程度\n2. 准备材料\n3. 修复损坏\n4. 表面处理',
    notes: '注意家具材质，选择合适的修复方法',
  },
]);

// 检查项数据
const inspectionItems = ref([
  {
    id: 1,
    category: 'safety',
    item: '安全防护措施',
    required: true,
    score: 10,
  },
  {
    id: 2,
    category: 'quality',
    item: '维修质量检查',
    required: true,
    score: 10,
  },
  {
    id: 3,
    category: 'cleanliness',
    item: '现场清洁',
    required: false,
    score: 5,
  },
  {
    id: 4,
    category: 'documentation',
    item: '维修记录完整',
    required: true,
    score: 5,
  },
]);

// 表格列定义
const columns = [
  {
    title: '标准名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '维修类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 80,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '评分',
    dataIndex: 'rating',
    key: 'rating',
    width: 120,
  },
  {
    title: '完成率',
    dataIndex: 'completionRate',
    key: 'completionRate',
    width: 120,
  },
  {
    title: '预计工时',
    dataIndex: 'estimatedHours',
    key: 'estimatedHours',
    width: 100,
    customRender: ({ text }: any) => `${text}小时`,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 检查项表格列定义
const itemColumns = [
  {
    title: '检查类别',
    dataIndex: 'category',
    key: 'category',
    width: 120,
  },
  {
    title: '检查项目',
    dataIndex: 'item',
    key: 'item',
    width: 200,
  },
  {
    title: '必检',
    dataIndex: 'required',
    key: 'required',
    width: 80,
  },
  {
    title: '分值',
    dataIndex: 'score',
    key: 'score',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
  },
];

// 过滤后的标准数据
const filteredStandards = computed(() => {
  let result = standards.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.priority) {
    result = result.filter((item) => item.priority === searchForm.priority);
  }

  return result;
});

// 状态和类型相关函数
const getStatusColor = (status: string) => {
  const colors = {
    active: 'green',
    inactive: 'red',
    draft: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts = {
    active: '启用',
    inactive: '停用',
    draft: '草稿',
  };
  return texts[status] || status;
};

const getTypeColor = (type: string) => {
  const colors = {
    electrical: 'blue',
    plumbing: 'cyan',
    appliance: 'purple',
    furniture: 'orange',
    structure: 'red',
    other: 'default',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts = {
    electrical: '电气维修',
    plumbing: '水管维修',
    appliance: '家电维修',
    furniture: '家具维修',
    structure: '结构维修',
    other: '其他',
  };
  return texts[type] || type;
};

const getPriorityColor = (priority: string) => {
  const colors = {
    low: 'green',
    medium: 'blue',
    high: 'orange',
    urgent: 'red',
  };
  return colors[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
  };
  return texts[priority] || priority;
};

const getCompletionStatus = (rate: number) => {
  if (rate >= 90) return 'success';
  if (rate >= 70) return 'normal';
  return 'exception';
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    priority: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    if (isEdit.value) {
      message.success('标准更新成功');
    } else {
      message.success('标准添加成功');
    }
    showAddModal.value = false;
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  resetForm();
};

const handleSaveItems = () => {
  message.success('检查项保存成功');
  showItemsModal.value = false;
};

const viewDetail = (record: any) => {
  selectedStandard.value = record;
  showDetailModal.value = true;
};

const editStandard = (record: any) => {
  isEdit.value = true;
  Object.assign(form, record);
  showAddModal.value = true;
};

const viewItems = (record: any) => {
  selectedStandard.value = record;
  showItemsModal.value = true;
};

const activateStandard = (record: any) => {
  message.success(`标准 ${record.name} 已启用`);
};

const deactivateStandard = (record: any) => {
  message.success(`标准 ${record.name} 已停用`);
};

const addItem = () => {
  const newItem = {
    id: Date.now(),
    category: '',
    item: '',
    required: false,
    score: 5,
  };
  inspectionItems.value.push(newItem);
};

const removeItem = (index: number) => {
  inspectionItems.value.splice(index, 1);
};

const resetForm = () => {
  Object.assign(form, {
    name: '',
    type: '',
    priority: 'medium',
    status: 'active',
    description: '',
    steps: '',
    estimatedHours: '',
    tools: '',
    notes: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = standards.value.length;
});
</script>

<style scoped>
.maintenance-standards {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.standard-info {
  display: flex;
  flex-direction: column;
}

.standard-name {
  margin-bottom: 4px;
  font-weight: 500;
}

.standard-desc {
  font-size: 12px;
  color: #666;
}

.rating-info {
  display: flex;
  gap: 4px;
  align-items: center;
}

.rating-score {
  font-weight: 500;
  color: #faad14;
}

.rating-count {
  font-size: 12px;
  color: #666;
}

.items-header {
  margin-bottom: 16px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: 500;
}
</style>
